/**
 * @author lulongwen
 * Date: 2023-08-27 22:10
 * Description:
 */

import { memo } from 'react';
import { Handle, useReactFlow, useStoreApi, Position } from 'reactflow';
import { Select as AntdSelect } from 'antd';

const options = [
  {
    value: 'smoothstep',
    label: 'Smoothstep',
  },
  {
    value: 'step',
    label: 'Step',
  },
  {
    value: 'default',
    label: 'Bezier (default)',
  },
  {
    value: 'straight',
    label: 'Straight',
  },
];

function Select({ value, handleId, nodeId }) {
  const { setNodes } = useReactFlow();
  const store = useStoreApi();

  const onChange = (e) => {
    const { nodeInternals } = store.getState();
    setNodes(
      Array
        .from(nodeInternals.values())
        .map((node) => {
          if (node.id === nodeId) {
            node.data = {
              ...node.data,
              selects: {
                ...node.data.selects,
                [handleId]: e,
              },
            };
          }
          return node;
        }),
    );
  };

  return (
    <div className='custom-node__select'>
      <span className='block mb-1'>EdgeType 连线类型</span>
      <AntdSelect
        className='nodrag w-full'
        value={value}
        onChange={onChange}
        size='small'
        options={options}
      />
      <Handle type='source' position={Position.Right} id={handleId} />
    </div>
  );
}

function CustomNode({ id, data }) {
  return (
    <>
      <div className='custom-node__header'>
        自定义节点 Nodes
      </div>
      <div className='custom-node__body'>
        {Object.keys(data.selects).map((handleId) => (
          <Select
            key={handleId}
            nodeId={id}
            value={data.selects[handleId]}
            handleId={handleId}
          />
        ))}
      </div>
    </>
  );
}

export default memo(CustomNode);
